package com.group01.community.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.group01.community.entity.ZyUnit;
import com.group01.community.entity.vo.ZyUnitVo;
import com.group01.community.service.ZyUnitService;
import com.group01.community.utils.ResponseResult;
import com.group01.community.utils.ResponseStatus;
import com.group01.community.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 单元  前端控制器
 * </p>
 *
 * @author iuoly
 * @since 2022-07-04
 */
@Slf4j
@Api(tags = "单元信息")
@RestController
@RequestMapping("/zyUnit")
public class ZyUnitController {
    @Autowired
    private ZyUnitService zyUnitService;

    /**
     * 分页条件查询单元信息
     * @param communityId 小区id
     * @param unitName 单元名称
     * @param unitCode 单元编号
     * @return 单元信息
     */
    @ApiOperation("分页条件查询单元信息")
    @GetMapping("/list")
    public ResponseResult<IPage<ZyUnitVo>> getAllZyUnitByDeptId(int curr, int size, Long communityId, Long buildingId, String unitName, String unitCode) {
        try {
            IPage<ZyUnitVo> units = zyUnitService.getUnitPage(curr, size, communityId, buildingId, unitName, unitCode);
            return new ResponseResult<IPage<ZyUnitVo>>(ResponseStatus.OK, units);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseResult<IPage<ZyUnitVo>>(ResponseStatus.PARAM_ERROR, null);
    }

    /**
     * 查询所有单元信息
     * @return 单元信息
     */
    @ApiOperation("查询所有单元信息")
    @GetMapping("/listAll/{buildingId}")
    public ResponseResult<List<ZyUnit>> getAllZyUnit(@PathVariable Long buildingId) {
        try {
            return new ResponseResult<List<ZyUnit>>(ResponseStatus.OK, zyUnitService.list(new QueryWrapper<ZyUnit>().eq("building_id", buildingId)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseResult<List<ZyUnit>>(ResponseStatus.INTERNAL_ERROR, null);
    }

    /**
     * 新增单元信息
     * @param zyUnit
     * @return
     */
    @ApiOperation("新增单元信息")
    @PostMapping("/add")
    public ResponseResult<String> add(@RequestBody ZyUnit zyUnit) {
        zyUnit.setUnitCode(UUIDUtils.getUnitCode());
        zyUnit.setCreateTime(LocalDateTime.now());
        zyUnitService.save(zyUnit);
        return new ResponseResult<String>(ResponseStatus.OK, "新增单元成功");
    }

    /**
     * 修改单元信息
     * @param zyUnit
     * @return
     */
    @ApiOperation("修改单元信息")
    @PutMapping("/update")
    public ResponseResult<String> update(@RequestBody ZyUnit zyUnit) {
        zyUnit.setUpdateTime(LocalDateTime.now());
        zyUnitService.updateById(zyUnit);
        return new ResponseResult<String>(ResponseStatus.OK, "修改单元成功");
    }

    /**
     * 删除单元信息
     * @param ids
     * @return
     */
    @ApiOperation("删除单元信息")
    @DeleteMapping("/delete/{ids}")
    public ResponseResult<String> delete(@PathVariable List ids) {
        zyUnitService.removeByIds(ids);
        return new ResponseResult<String>(ResponseStatus.OK, "删除单元成功");
    }

    /**
     * 导出当前页所有单元信息
     * @param response
     * @throws IOException
     */
    @ApiOperation("导出当前页所有单元信息")
    @GetMapping("/export")
    public void export(HttpServletResponse response, int curr, int size, Long communityId, Long buildingId, String unitName, String unitCode) throws IOException {
        ExcelWriter writer= null;
        ServletOutputStream outputStream= null;
        try {
            //查询当前页面所有单元
            List<ZyUnitVo> all = zyUnitService.getUnitPage(curr, size, communityId, buildingId, unitName, unitCode).getRecords();

            //在内存操作，写到浏览器
            writer = ExcelUtil.getWriter(true);

            //自定义标题别名
            writer.addHeaderAlias("unitId", "单元id");
            writer.addHeaderAlias("communityId", "小区id");
            writer.addHeaderAlias("buildingId", "楼栋id");
            writer.addHeaderAlias("unitName", "单元名称");
            writer.addHeaderAlias("unitCode", "单元编码");
            writer.addHeaderAlias("unitLevel", "层数");
            writer.addHeaderAlias("unitAcreage", "建筑面积");
            writer.addHeaderAlias("unitHaveElevator", "是否有电梯");
            writer.addHeaderAlias("createBy", "创建者");
            writer.addHeaderAlias("createTime", "创建时间");
            writer.addHeaderAlias("remark", "备注");

            //默认配置
            writer.write(all,true);
            // 设置只导出别名列
            writer.setOnlyAlias(true);
            //设置content—type
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");

            //设置标题
            String fileName= URLEncoder.encode("单元信息","UTF-8");
            //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
            response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //将Writer刷新到OutPut
            writer.flush(outputStream,true);
            outputStream.close();
            writer.close();
        }
    }
}

